package com.aatrox.bhsypro.controller;

import com.aatrox.bhsypro.entity.BScolumn;
import com.aatrox.bhsypro.entity.BUser;
import com.aatrox.bhsypro.entity.UserTalk;
import com.aatrox.bhsypro.service.BScolumnService;
import com.aatrox.bhsypro.service.BUserService;
import com.aatrox.bhsypro.service.UserTalkService;
import com.aatrox.bhsypro.util.CookieUtil;
import com.aatrox.bhsypro.util.JsonResult;
import com.aatrox.bhsypro.util.QiniuUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/zl")
//@SessionAttributes({"bUser"})
public class ZhuanLangAjaxController {
    protected static final Logger logger = LoggerFactory.getLogger(ZhuanLangAjaxController.class);

    @Autowired
    BScolumnService bss;
    @Autowired
    BUserService bUserService;
    @Autowired
    UserTalkService userTalkService;
    @Autowired
    BScolumnService bScolumnService;

    /**
     * 上传专栏
     * @param sName
     * @param hm
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(path = "/contents",method = RequestMethod.POST)
    public JsonResult contents(String sName,String zlTag,String hm,MultipartFile[] file,HttpServletRequest request,HttpSession session){
        HashMap hmap = new HashMap();
        String zlImg = "";
        if (file!=null){
            String fpath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            File upload = new File(fpath,"static/images/upload/");
            if(!upload.exists()) upload.mkdirs();
            String path = "";
            for (int i = 0; i < file.length ; i++) {
                path = upload.getAbsolutePath()+"\\"+file[i].getOriginalFilename();
                logger.info("----图片路径为:"+path);
                String huizhui = path.substring(path.indexOf("."));
                if (!".jpg".equals(huizhui) && !".png".equals(huizhui)){
                    return new JsonResult(500,"只能上传jpg，png图片文件",null);
                }
                File f = new File(path);
                //移动图片
                try {
                    file[i].transferTo(f);
                    //上传图片到七牛云
                    String url = QiniuUpload.upload(f);
                    //把上传给七牛云返回的文件名存到user对象中，你可以根据情况处理
                    System.out.println(url+"7云牛图片名字");
                    if (i==file.length-1){
                        zlImg+=url;
                    }else {
                        zlImg+=url+",";
                    }

                    //移除图片
                    f.delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String ticket = CookieUtil.getCookieValue(request,"userTicket");
        BUser user = (BUser) redisTemplate.opsForValue().get("user:"+ticket+"uid:"+(session.getAttribute("buserId")));
        BScolumn bs = new BScolumn(user.getUid(),sName,hm,zlImg,zlTag);
        bss.insertNewZl(bs);
        logger.info("专栏图片: "+zlImg);
        hmap.put("zlHtml",hm);
        logger.info("进入contents层的log");
        logger.info("HTML:----------"+hm);
        return new JsonResult(200,"123",hmap);
    }
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    /**
     * http://r1xjdohxw.hn-bkt.clouddn.com/
     * @return
     */
    @RequestMapping(path = "/Bhscolumn/{uid}/{sid}/{sName}",method = RequestMethod.GET)
    public JsonResult scolumn(@PathVariable("uid") int uid , @PathVariable("sid") int sid, @PathVariable("sName") String sName, ModelMap map, HttpServletRequest request,HttpSession session){
        String ticket = CookieUtil.getCookieValue(request,"userTicket");
        BUser user = (BUser) redisTemplate.opsForValue().get("user:"+ticket+"uid:"+(session.getAttribute("buserId")));
        BUser bus=bUserService.selUserForUid(user.getUid());
        logger.info("UID:"+uid);
        logger.info("SName:"+sName);
        System.out.println(map.get("bUser"));
        HashMap hm = new HashMap();
        hm.put("uid",uid);
        hm.put("sid",sid);
        hm.put("sName",sName);
        BScolumn bs = bss.selScolumn(hm);
        BUser bu=bUserService.selUserForUid(uid);
        hm.clear();
        hm.put("bscolumn",bs);
        hm.put("buser",bu);
        hm.put("bus",bus);
        return new JsonResult(200,"查询专栏",hm);
    }
    @RequestMapping("/pl")
    public JsonResult selbyid(int vsid, String tmsg,HttpServletRequest request, ModelMap map,HttpSession session){
        String ticket = CookieUtil.getCookieValue(request,"userTicket");
        BUser user = (BUser) redisTemplate.opsForValue().get("user:"+ticket+"uid:"+(session.getAttribute("buserId")));
        UserTalk u=new UserTalk(vsid,user.getUid(),tmsg,3,new Date(),0,0);
        int i=userTalkService.insertNewTalk(u);
        BUser bUser=bUserService.selUserForUid(user.getUid());
        System.out.println(bUser);
        HashMap hm = new HashMap();
        hm.put("bUser",bUser);
        return new JsonResult(200,"成功",hm);
    }
    @ResponseBody
    @RequestMapping(path = "/dz",method = RequestMethod.PUT)
    public JsonResult updz(int tid){
        System.out.println("sfaasfa");
        int i=userTalkService.upnyid(tid);
        return new JsonResult(200,"成功");
    }
    @ResponseBody
    @RequestMapping(path = "/cp",method = RequestMethod.PUT)
    public JsonResult upcp(int tid){
        System.out.println("sfaasfa");
        int i=userTalkService.upcpnyid(tid);
        return new JsonResult(200,"成功");
    }
    @ResponseBody
    @RequestMapping(path = "/zldz",method = RequestMethod.PUT)
    public JsonResult zldz(int sid){
        int i=bScolumnService.upbysid(sid);

        return  new JsonResult(200,"成功");

    }

    @RequestMapping("/zhiBo")
    public JsonResult zhiBo(HttpServletRequest request,HttpSession session){
        String ticket = CookieUtil.getCookieValue(request,"userTicket");
        BUser user = (BUser) redisTemplate.opsForValue().get("user:"+ticket+"uid:"+(session.getAttribute("buserId")));
        String zBuser = (String) redisTemplate.opsForValue().get("ZhiBoV");
        String uid = "";
        if (zBuser==null){
            uid = String.valueOf(user.getUid());
            redisTemplate.opsForValue().set("ZhiBoV",uid);
        }else {
            for (int i = 0; i < zBuser.split(",").length ; i++) {
                if (zBuser.split(",")[i].equals(String.valueOf(user.getUid()))){
                    return new JsonResult(201,"直接已经存在咯",null);
                }
            }
            uid = zBuser + ","+user.getUid();
            redisTemplate.opsForValue().set("ZhiBoV",uid);
        }
        return new JsonResult(202,"直播间已经生成,快去直播吧",null);
    }
}
